#!/usr/bin/env python3

import matplotlib
import networkx
import os
import argparse
import re


def construct_digraph_from_dot(dot: str)->networkx.DiGraph:
    if not os.path.isfile(os.path.abspath(dot)):
        print("dot path is invalid.")
        exit(1)
    node_pattern='\"(node[0-9]+)\"'
    edge_pattern='\s*'+node_pattern+''+'\s*->\s*'+''+node_pattern+'.*'
    node_create_pattern='\s*'+node_pattern+'\s*\[\s*'+'label=\"([\w-]*)\"'+'\s*.*'
    module_graph=networkx.DiGraph()
    nodes=[]
    edges=[]
    node2module={}
    dot_file=open(dot,'r')
    line=dot_file.readline()
    while line:
        matchObj=re.match(edge_pattern,line)
        if not matchObj==None:
            # pass
            # print("from node: "+matchObj.group(1),end='\t')
            # print("to node: "+matchObj.group(2))
            edges.append((matchObj.group(1),matchObj.group(2)))
        else:
            matchObj=re.match(node_create_pattern,line)
            if not matchObj==None:
                # print("create node: "+matchObj.group(1)+'\t->\t'+matchObj.group(2))
                node_index=matchObj.group(1)
                node_name=matchObj.group(2)
                node2module[node_index]=node_name
                nodes.append(node_index)
                # print(line)
        line=dot_file.readline()
        # break
    # for node in nodes:
    #     print('node: '+node+'\t->\t'+node2module[node])
    module_graph.add_nodes_from(nodes)
    module_graph.add_edges_from(edges)
    # networkx.draw_networkx(module_graph)
    
    
        

if __name__=='__main__':
    parser=argparse.ArgumentParser(description='group entities in module and extract link dependency')
    parser.add_argument(
        '--dot',
        '-d',
        type=str,
        help='path to .dot file'
    )
    args=parser.parse_args()
    construct_digraph_from_dot(args.dot)